﻿@inject IUserService _userService
@inject IPopupService PopupService
@inject IHttpService _httpService
@inject NavigationManager NavigationManager
@inject IPageModelCatche<UserSpaceViewModel> _pageModelCatche
@inject IPageModelCatche<List<StallInfoViewModel>> _stallPageModelCatche
@inject IPageModelCatche<StallViewModel> _indexPageModelCatche

@implements IDisposable

<MDCard Class="stall-info-card mb-4 pa-4">
    <MDCard Outline Class="user-card on-background-text" Href="@($"/user/space/{Model.CreateUser.Id}/0")">
         <CnGalWebSite.Components.Images.MasaImage Src="@Model.CreateUser.Avatar" Alt="@Model.CreateUser.Name" Type="ImageType.Avatar" />
         <div class="name-card">
             <div class="title-medium">@(Model.CreateUser.GetName(UserType.Person))</div>
             <div class="label-large text-truncate-1">@(Model.CreateUser.PersonDescription)</div>
         </div>
     </MDCard>
     <div class="item-card">
         <div class="label-large">橱窗价格</div>
         <div class="title-large primary-text">@($"￥ {Model.Price}")</div>
     </div>
     <div class="item-card">
         <div class="label-large">截止日期</div>
         <div class="title-large primary-text">@Model.EndTime.ToString("yyyy-MM-dd")</div>
    </div>


    @if (_userService.UserInfo.Id == Model.CreateUser.Id)
    {
        <div class="action-card">
            <CnGalWebSite.Components.Buttons.MasaButton Icon="@IconType.Edit.ToIconString()" Text="编辑橱窗" Rounded Href="@($"/stall/edit/{Model.Id}")" />
             <CnGalWebSite.Components.Buttons.MasaButton TextStyle Icon="@IconType.Delete.ToIconString()" Text="删除" OnClick="OnDelete" />
         </div>
    }
    @if (_userService.UserInfo.Id != Model.CreateUser.Id)
    {
        <div class="action-card">
            <AuthorizeView>
                <Authorized>
                    <CnGalWebSite.Components.Buttons.MasaButton Rounded="!Model.Users.Any(s=>s.User.Id==_userService.UserInfo.Id)" TextStyle="Model.Users.Any(s=>s.User.Id==_userService.UserInfo.Id)" IsAsync
                                                                 Text="@(Model.Users.Any(s=>s.User.Id==_userService.UserInfo.Id)?"取消邀请":"邀请")"
                                                                 Icon="@(Model.Users.Any(s=>s.User.Id==_userService.UserInfo.Id)?@IconType.Close.ToIconString():@IconType.Flag.ToIconString())" OnClick="OnClick" />
                 </Authorized>
                 <NotAuthorized>
                     <CnGalWebSite.Components.Buttons.MasaButton Text="登入后邀请" Icon="@IconType.Login.ToIconString()" Rounded OnClick="_userService.Login" />
                 </NotAuthorized>
             </AuthorizeView>

         </div>
    }
</MDCard>
<CnGalWebSite.Components.Verifications.DeviceIdentification @ref="deviceIdentification" />

@code {
    [Parameter]
    public StallViewModel Model { get; set; }

    [Parameter]
    public EventCallback OnChanged { get; set; }

    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }
    CnGalWebSite.Components.Verifications.DeviceIdentification deviceIdentification;

    protected override void OnInitialized()
    {
        _userService.UserInfoChanged -= OnUserInfoChanged;
        _userService.UserInfoChanged += OnUserInfoChanged;
    }

    public void OnUserInfoChanged()
    {
        StateHasChanged();
    }

    public async Task OnDelete()
    {
        var confirmed = await PopupService.ConfirmAsync("删除橱窗", "删除橱窗将会清空所有相关数据，确定要删除吗？", AlertTypes.Error);
        if (confirmed == false)
        {
            return;
        }

        string operationName = "删除橱窗";
        try
        {
            var obj = await _httpService.PostAsync<HideModel, Result>("api/stall/Hide", new HideModel { Id = Model.Id, Hide = true });

            if (obj.Success == false)
            {
                await PopupService.ToastAsync(operationName + "失败", AlertTypes.Error);
            }
            else
            {
                await PopupService.ToastAsync(operationName + "成功", AlertTypes.Success);
                _stallPageModelCatche.Clean($"api/stall/getall");
                _indexPageModelCatche.Clean($"api/stall/get?id={Model.Id}");
                _pageModelCatche.Clean($"api/user/GetUserSpace?id={_userService.UserInfo.Id}");
                NavigationManager.NavigateTo("/stall");
            }
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, operationName + "失败");
        }

    }

    public async Task OnClick()
    {
        var apply = !Model.Users.Any(s => s.User.Id == _userService.UserInfo.Id);
        var _name = apply ? "邀请" : "取消邀请";
        try
        {
            var obj = await _httpService.PostAsync<ApplyStallModel, Result>("api/stall/ApplyStall", new ApplyStallModel
                {
                    StallId = Model.Id,
                    Apply = apply,
                    Identification = await deviceIdentification.GetDeviceIdentificationModel()
                });
            //判断结果
            if (obj.Success == false)
            {
                await PopupService.ToastErrorAsync($"{_name}失败", obj.Message);
            }
            else
            {
                await PopupService.ToastSuccessAsync($"{_name}成功");
                await OnChanged.InvokeAsync();
            }
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, $"{_name}失败");
        }
    }

    public void Dispose()
    {
        _userService.UserInfoChanged -= OnUserInfoChanged;
        GC.SuppressFinalize(this);
    }
}
